package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smarthospital.dao.im.daoService.IMMessageDaoService;
import com.smarthospital.entity.im.IMMessage;
import com.smarthospital.service.IMMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * create by sym  2021/5/19 19:30.
 */
@Slf4j
@Service
public class IMMessageServiceImpl implements IMMessageService {

    @Autowired
    private IMMessageDaoService imMessageDaoService;

    /**
     * 接入连接  onOpen 拉出房间历史信息 并附加 "以上是历史记录" 从session中判断当前用户信息  调整消息已读、未读状态
     * @param sessions 当前房间所有session
     * @param session 连接用户session
     * @param orderId 订单id 也是房间id
     */
    @Override
    public void onOpen(CopyOnWriteArraySet<Session> sessions,Session session, String orderId) {

        Page<IMMessage> page = imMessageDaoService.getByOrderId(orderId);
        String senderId = session.getPathParameters().get("senderId");
        //接收的消息不用管未读已读
        List<IMMessage> pageContent = page.getContent();
        List<IMMessage> list = new ArrayList(pageContent);
        list.forEach((msg)->{ if(msg.getReceiverId().equals(senderId)){msg.setStatus(2);}});
        list.add(IMMessage.TIP_ON_OPEN);
        try {
            //拉取历史消息
            session.getBasicRemote().sendText(JSON.toJSONString(list));
            //需不需要告知对方 我已上线？ todo
        } catch (IOException e) {
            log.error("websocket IO异常 e {}",e.getMessage(),e);
        }
    }

    /**
     * 接收消息    判断对方是否在线，如果不在线  将消息存入ES中(未读) 如果在线  将消息存入ES中(已读) 并发送给对方
     * @param sessions
     * @param session
     * @param message 发送过来的消息，应该也是json体
     */
    @Override
    public void onMessage(String orderId,CopyOnWriteArraySet<Session> sessions, Session session, String message) {
        IMMessage imMessage = JSONObject.parseObject(message, IMMessage.class);
        imMessage.setOrderId(orderId);

//        imMessage.setSenderId(session.getPathParameters().get("senderId"));
//        imMessage.setReceiverId(session.getPathParameters().get("receiverId"));
        sessions.remove(session);
        // todo 目前用sessionId代替
        imMessage.setSenderId(session.getId());
        for (Session session1 : sessions) {
            imMessage.setReceiverId(session1.getId());
        }



        //对方在线
        if (!sessions.isEmpty()) {
            imMessage.setStatus(1);
        }
        imMessageDaoService.save(imMessage);
        List list = new ArrayList(1);
        list.add(imMessage);
        try {
            for (Session session1 : sessions) {
                session1.getBasicRemote().sendText(JSON.toJSONString(list));
            }

        } catch (IOException e) {
            log.error("websocket IO异常 e {}",e.getMessage(),e);
        }

    }

}
